package com.woniu.redisson;

import org.redisson.Redisson;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * redis锁的获取与释放
 */
public class DistributedRedisLock {
    //从Redisson配置类中获取redisson对象
    private static Redisson redisson = RedissonManager.getRedisson();
    private static final String LOCK_TITLE = "redisLock_";

    /**
     * 上锁
     */
    public static Boolean acquire(String lockName) {
        //声明key对象
        String key = LOCK_TITLE + lockName;
        //获取锁对象(用getLock即可开启watchdog,默认30s,每10s监控)
        RLock myLock = redisson.getLock(key);
        //加锁,设置锁过期时间为3s,防止死锁,uuid+threadId
        myLock.lock(10L, TimeUnit.SECONDS);
        //加锁成功
        return true;
    }

    /**
     * 锁的释放
     */
    public static void release(String lockName) {
        //必须是和加锁时间是同一个key
        String key = LOCK_TITLE + lockName;
        //获取锁对象
        RLock myLock = redisson.getLock(key);
        //释放锁(解锁)
        myLock.unlock();
    }
}
